package com.idealighter.game.chat.manager;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.idealighter.game.common.CommonMsgMgr;
import com.idealighter.game.core.constant.Operator;
import com.idealighter.game.core.constant.SysConfigId;
import com.idealighter.game.core.error.ErrorCode;
import com.idealighter.game.dictionary.dic.SysconfigDic;
import com.idealighter.game.dictionary.dic.WordsDic;
import com.idealighter.game.player.struct.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 聊天管理 .
 * 
 * @date 2015年11月13日 下午1:58:07
 *
 */
@Singleton
public class ChatMgr {

  private static final Logger LOG = LoggerFactory.getLogger(ChatMgr.class);

  // 聊天内容长度
  public static final int CONTENT_LENGTH = 50;

  @Inject
  private ChatMsgMgr chatMsgMgr;
  @Inject
  private SysconfigDic sysconfigDic;
  @Inject
  private CommonMsgMgr commonMsgMgr;
  @Inject
  private WordsDic wordsDic;

  /**
   * 同房间聊天 .
   * 
   * @param player 玩家.
   * @param content .
   */
  public void roomChat(Player player, String content) {
    if (sysconfigDic.getIntVal(SysConfigId.CHAT_IN_ROOM) == 0) {
      commonMsgMgr.sendErrorDlgMsg(player, ErrorCode.GAME_NOT_ALLOW_CHAT, Operator.SYSTEM);
      return;
    }

    if (!checkContent(player, content)) {
      return;
    }

    if (player.curRoom != null) {
      chatMsgMgr.sendRoomChatMsg(player, filterContent(content));
    }
  }

  /**
   * 同桌聊天 .
   * 
   * @param player 玩家.
   * @param content .
   */
  public void tableChat(Player player, String content) {
    if (sysconfigDic.getIntVal(SysConfigId.CHAT_IN_TABLE) == 0) {
      commonMsgMgr.sendErrorDlgMsg(player, ErrorCode.GAME_PLAYING_NOT_ALLOW_CHAT,
          Operator.SYSTEM);
      return;
    }

    if (!checkContent(player, content)) {
      return;
    }

    for (String word : wordsDic.words()) {
      content.replaceAll(word, "***");
    }

    if (player.curTable != null) {
      chatMsgMgr.sendTableChatMsg(player, filterContent(content));
    }
  }

  /**
   * 校验聊天内容 .
   * 
   * @param player 玩家.
   * @param content .
   * @return .
   */
  private boolean checkContent(Player player, String content) {
    if (content == null || content.trim().length() == 0) {
      return false;
    }

    if (content.length() > CONTENT_LENGTH) {
      LOG.error("玩家[{}][{}]聊天内容长度超过100", player.getPlayerName(), player.getId());
      return false;
    }

    return true;
  }

  /**
   * 过滤字符串(去掉敏感词汇) .
   * 
   * @param content .
   * @return .
   */
  public String filterContent(String content) {
    for (String word : wordsDic.words()) {
      content = content.replaceAll(word, "***");
    }

    return content;
  }
}
